/* 代理报名/人员变更 */
<template>
    <div>
        <div style="height: 30px;">
            <el-breadcrumb style="float: left;" separator="/">
                <el-breadcrumb-item :to="{ path: compile === 'individual'? '/registrationListIndividual': '/registrationListTeam' }">
                    <span @click="reback">{{ $t('registrationList.competitionProjectRegistration') }}</span>
                </el-breadcrumb-item>
                <el-breadcrumb-item>{{ compile === 'individual'? $t('registrationList.agentRegistration') : $t('registrationList.personnelChange') }}</el-breadcrumb-item>
            </el-breadcrumb>
        </div>

        <el-card v-loading="loading" shadow="never" body-style="padding: 10px;">
            <el-row style="padding:15px 15px 15px 15px;" class="row-bg" justify="space-between">
                <span style="font-size:20px; color:#101010;">
                    {{ compile === 'individual'? $t('registrationList.competitionProjectAgentRegistration') : $t('registrationList.competitionProjectPersonnelChange') }}
                </span>
                <el-button style="float:right; margin-left:10px;" @click="reback">
                    {{ $t('statisticsOfAwards.goBack') }}
                </el-button>
            </el-row>
            <!-- <hr > -->
            <condition-card @reset="reset" @search="onSubmit" label-position="right" label-width="150px">
                <el-form ref="queryForm" :model="queryForm" label-width="120px">
                    <el-row :gutter="24" style="height: 50px;">
                        <!-- 年级 -->
                        <el-col :span="8">
                            <el-form-item :label="$t('competitionRegistrationRules.grade')">
                                <el-date-picker style="width:100%"
                                v-model="queryForm.condition.grade"
                                :placeholder="$t('competitionRegistrationRules.pleaseSelect')"
                                type="year" value-format="yyyy" format="yyyy">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <!-- 学院 --> 
                        <el-col :span="8">
                            <el-form-item :label="$t('registrationList.college')">
                                <DictSelect v-model="queryForm.condition.faculty" filterable :data="options.faculty" :plzSelect="true"></DictSelect>          
                            </el-form-item>
                        </el-col>
                        <!-- 学号 -->
                        <el-col :span="8">
                            <el-form-item :label="$t('registrationList.studentList')">
                                <el-input
                                    v-model.trim="queryForm.condition.studentId"
                                    :placeholder="$t('registrationList.pleaseEnterStudentList')"
                                    prefix-icon="el-icon-search"
                                    @keyup.enter.native="queryStudents"
                                />
                            </el-form-item>
                        </el-col>
                        <!-- 学号 -->
                        <!-- <el-col :span="8">
                            <el-form-item :label="$t('registrationList.studentId')">
                                <el-input
                                    v-model="queryForm.condition.studentId"
                                    placeholder="请输入学生学号/姓名搜索"
                                    @keyup.enter.native="onSubmit"
                                    style="width: 100%"
                                >
                                    <i
                                        class="el-icon-search"
                                        slot="suffix"
                                        style="margin-top:10px;cursor:pointer"
                                        @click="onSubmit"
                                    ></i>
                                </el-input>
                            </el-form-item>
                        </el-col> -->
                    </el-row>
                    <el-row :gutter="24" style="height: 50px;">
                        <!-- 姓名 -->
                        <!-- <el-col :span="8">
                            <el-form-item :label="$t('registrationList.studentName')">
                                <el-input v-model="queryForm.condition.studentName" style="width: 100%" />
                            </el-form-item>
                        </el-col> -->
                        <!-- 年度 -->
                        <el-col :span="8" v-if="compile === 'individual'">
                            <el-form-item :label="$t('registrationList.competitionYear')">
                                <el-date-picker style="width:100%"
                                    v-model="queryForm.condition.year"
                                    @change="changeYear"
                                    :placeholder="$t('registrationList.pleaseSelectYear')"
                                    type="year" value-format="yyyy" format="yyyy">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <!-- 竞赛名称 -->
                        <el-col :span="8" v-if="compile === 'individual'">
                            <el-form-item :label="$t('registrationList.competitionNames')">
                                <el-select collapse-tags  v-model="queryForm.condition.competitionId"  @change="changeSubname" filterable clearable remote :remote-method="remoteMethodName" style="width: 100%">
                                    <el-option  v-for="item in options.competitionNames" :key="item.value" :label="item.label" :value="item.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <!-- 竞赛小类 -->
                        <el-col :span="8">
                            <el-form-item :label="$t('registrationList.competitionCate')" v-if="compile === 'individual' && options.subName.length>0">
                                <el-select v-model="queryForm.condition.subName" filterable clearable style="width: 100%">
                                    <el-option
                                        v-for="item in options.subName"
                                        :key="item.id"
                                        :label="item.subName"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </condition-card>
            
            <el-row :gutter="20" style="margin: 30px 20px">
                <el-col :span="11">
                    <el-table
                        ref="staffTable"
                        v-loading="listLoading"
                        :data="staffList"
                        border
                        fit
                        height="360"
                        stripe
                        :row-key="getRowKey"
                        :header-cell-style="{background:'#EDF1F5'}"
                        highlight-current-row
                        @selection-change="handleStaffChange"
                    >
                        <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
                        <el-table-column type="index" label="序号" width="50"></el-table-column>
                        <el-table-column :label="$t('registrationList.studentId')" width="100" show-overflow-tooltip align="center" prop="code"></el-table-column>
                        <el-table-column :label="$t('registrationList.studentName')" width="100" show-overflow-tooltip align="center" prop="name"></el-table-column>
                        <el-table-column :label="$t('registrationList.sex')" width="100" show-overflow-tooltip align="center" prop="sex"></el-table-column>
                        <el-table-column :label="$t('registrationList.college')" width="120" show-overflow-tooltip align="center" prop="faculty"></el-table-column>
                        <el-table-column :label="$t('registrationList.telephoneNumber')"  width="120" show-overflow-tooltip align="center" prop="telephone"></el-table-column>
                        <el-table-column :label="$t('registrationList.mail')" width="120" show-overflow-tooltip align="center" prop="mail"></el-table-column>
                    </el-table>
                </el-col>
                <el-col :span="2" style="text-align:center;margin-top:110px">
                    <!-- <el-button
                        @click="addStaff"
                    >{{ '重置' }}</el-button> -->
                    <el-button
                        @click="addStaff"
                        type="primary"
                        icon="el-icon-arrow-right"
                        style="margin-left: 0;margin-top: 10px;"
                    ></el-button>
                    <el-button
                        @click="removeStaff"
                        type="primary"
                        icon="el-icon-arrow-left"
                        style="margin-left: 0;margin-top: 10px;"
                    ></el-button>
                </el-col>
                <el-col :span="11">
                    <el-table
                        ref="selectedStaffTable"
                        v-loading="listLoading"
                        :data="selectedStaffList"
                        height="360"
                        border
                        fit
                        stripe
                        :row-key="getRowKey"
                        :header-cell-style="{background:'#EDF1F5'}"
                        highlight-current-row
                        @selection-change="handleSelectedStaffChange"
                    >
                        <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
                        <el-table-column type="index" label="序号" width="50"></el-table-column>
                        <el-table-column :label="$t('registrationList.studentId')" width="100" show-overflow-tooltip align="center" prop="code"></el-table-column>
                        <el-table-column :label="$t('registrationList.studentName')" width="100" show-overflow-tooltip align="center" prop="name"></el-table-column>
                        <el-table-column :label="$t('registrationList.sex')" width="100" show-overflow-tooltip align="center" prop="sex"></el-table-column>
                        <el-table-column :label="$t('registrationList.college')" width="120" show-overflow-tooltip align="center" prop="faculty"></el-table-column>
                        <el-table-column :label="$t('registrationList.telephoneNumber')" width="120" show-overflow-tooltip align="center" prop="telephone"></el-table-column>
                        <el-table-column :label="$t('registrationList.mail')" width="120" show-overflow-tooltip align="center" prop="mail"></el-table-column>
                        <el-table-column :label="$t('registrationList.type')" align="center" fixed="right" v-if="compile === 'team'" width="120">
                            <template slot-scope="scope">
                                <!-- <el-select class="filter-item" placeholder="请选择" v-model="row.staffTypeId">
                                <el-option
                                    v-for="item in staffOptions"
                                    :key="item.key"
                                    :label="item.display_name"
                                    :value="item.key"
                                ></el-option>
                                </el-select> -->
                                <el-radio v-model="radio" :label="scope.row.code" @change.native="getTemplateRow(scope.$index, scope.row)">{{ $t('registrationList.setLeader') }}</el-radio>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>
            </el-row>
            <div style="float: right; padding: 15px;">
                <el-button @click="reback">{{ $t('statisticsOfAwards.cancel') }}</el-button>
                <el-button type="primary" @click="save()"> {{ $t('statisticsOfAwards.save') }}</el-button>
            </div>
        </el-card>
    </div>
</template>

<script>
import { queryDic } from 'common/src/api/dictionary';
import UTILS from 'common/src/utils/utils';
import competiManagementApi from 'common/src/api/subjectCompetition/competiManagement';
import interManagementApi from 'common/src/api/externalExchange/interdiSciplinaryManagement';
import gradeApi from "common/src/api/calendars";
import { findStuInfoList } from 'common/src/api/studentinfo';
import competitionRegistrationApi from 'common/src/api/competitionRegistration/competitionRegistration';
import comRegistration from 'common/src/api/competitionRegistration/comRegistration'
export default {
    props: {
        compile: {
            type: String,
            default: ''
        },
        dataInfo: {
            type: Object,
            default: () => {},
        }
    },
    data() {
        let cannotEnter = (rule, value, callback) => {
            let reg = /[`$]/im
            if (reg.test(value)) {
                return callback(new Error(this.$t('statisticsOfAwards.donotEnterSpecial')))
            } else if (value === '' || value === null) {
                return callback(new Error(this.$t('statisticsOfAwards.pleaseEnter')))
            }
            return callback()
        }
        return {
            queryForm: {
                pageNum_: 1,
                pageSize_: 20,
                total_: 0,
                condition:{
                    subName: '',
                    form: this.compile === 'individual'? 0 : 1, // 竞赛类型(0个人1团体)
                    // year: new Date().getFullYear(),
                    grade: '', // 年级
                    year: new Date().getFullYear()+'',
                    faculty: '', // 学院
                    competitionId: '', // 竞赛名称
                    studentName: '', // 姓名
                    studentId: '', // 学号
                    status: '' // 状态(1.已报名 2.选拔中 3.选拔通过 4.已退出)
                }
            },
            options: {
                subName: [],
                faculty: [], // 学院
                approver: [],
                profession: [], // 竞赛名称
                degreeType: [], // 竞赛级别
                competitionNames: [] 
            },
            staffList: [],
            selectedStaffList: [],
            staffData: [],
            selectedStaffData: [],
            tableKey: 0,
            // rowKey: "rowKey",
            radio: '',
            defaultVal: '',
            studentList: [] // 报名学生信息
        }
    },
    mounted() {
        this.getOptions()
        this.getDefaultGrade()
        this.getCompetitionNames()
        if(this.compile === 'team') {
            this.getGroupInfo(this.dataInfo.signRecordId)
        }
    },
    methods: {
        changeSubname() {
            this.queryForm.condition.subName = ''
            this.options.subName = []
            let jsId = this.queryForm.condition.competitionId // 获取竞赛ID
            comRegistration.getSubCompetitions(jsId).then(res => {
                this.options.subName = res.data
            })
        },
        //查询当前年级
        async getDefaultGrade () {
            return await gradeApi.currentTermCalendar().then(res => {
                this.queryForm.condition.grade = res.data.schoolCalendar.year.toString()
                this.queryStudents()
            });
        },
        // 字典获取
        getOptions() {
            // 筛选条件字典查询
            let data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: ["X_PYCC", 'X_PYLB', 'X_XWLX', 'X_XXXS', 'X_YX', 'JSGL_JSJB']
            };
            queryDic(data).then(res => {
                UTILS.fillSelect(
                {
                    trainingCategory: "X_PYLB",
                    degreeType: "JSGL_JSJB",
                    formLearning: "X_XXXS",
                    faculty: "X_YX",
                    TrainingLevel: "X_PYCC"
                },
                res.data,
                this.options
                );
            });
        },
        // 学生信息查询
        queryStudents() {
            let query = {
                "condition":{
                    "codeOrName": this.queryForm.condition.studentId,
                    "currentGrade": this.queryForm.condition.grade,
                    "faculty": this.queryForm.condition.faculty
                },
                "pageSize_": 20,
                "pageNum_": 1,
            }
            competitionRegistrationApi.getStudentInfo(query).then((response) => {
                if (response.code == 200) {
                    this.staffList = response.data.list
                    // this.queryStudentForm.total = response.data.total_
                }
            })
        },
        // 人员变更学生信息查询
        getGroupInfo(query) {
            competitionRegistrationApi.getGroupInfo(query).then((response) => {
                if (response.code == 200) {
                    this.selectedStaffList = response.data
                    if(this.selectedStaffList.length > 0) {
                        this.selectedStaffList.forEach(value => {
                            if(value.isLeader === 1) {
                                this.radio = value.code
                            }
                        })
                    }
                    // this.queryStudentForm.total = response.data.total_
                }
            })
        },
        // 模糊查询竞赛名称
        remoteMethodName(val) {
            if (val !== '') {
                this.options.competitionNames = []
                this.queryForm.condition.competitionId = val
                this.getCompetitionNames()
            } else {
                this.options.competitionNames = []
            }
        },
        // 根据年度获取竞赛名称
        changeYear(val) {
            this.getCompetitionNames()
        },
        getCompetitionNames() {
            let param = {
                "pageNum_": 1,
                "pageSize_": 10,
                "condition":{
                    "projectName": this.queryForm.condition.competitionId,
                    "year": this.queryForm.condition.year,
                    "form": this.compile === 'team' ? 1 : 0
                }
            }
            this.options.competitionNames = []
            competitionRegistrationApi.getCompetitionNames(param).then(res => {
                if (res.data.list) {
                    res.data.list.forEach(el => {
                        this.options.competitionNames.push({
                            label: el.projectName,
                            value: el.id
                        })
                    })
                }
            })
        },
        // 设置队长
        getTemplateRow(index, row) {
            this.selectedStaffList.forEach( item => {
                if(item.isLeader === 1) {
                    item.isLeader = null
                }
                // if(row.code === item.code) {
                //     // item.isLeader = 1
                //     this.$set(row, 'isLeader', 1)
                // }
            })
            this.$set(row, 'isLeader', 1)
        },
        // 返回主页面
        reback() {
            this.$emit('change-exam')
        },
        getRowKey (row) {
            return row.id
        },
        // 将左边表格选择项存入staffData中
        handleStaffChange(rows) {
            this.staffData = [];
            if (rows) {
                rows.forEach(row => {
                    if (row) {
                        this.staffData.push(row)
                    }
                });
            }
        },
        // 左边表格选择项移到右边
        addStaff() {
            setTimeout(() => {
                this.$refs["staffTable"].clearSelection();
                this.$refs["selectedStaffTable"].clearSelection();
            }, 0);
            let repeat = false;
            if(this.staffData.length === 0) {
                return this.$message.error(this.$t('registrationList.pleaseSelectStudents'))
            }
            this.selectedStaffList.forEach(item => {
                if (this.staffData[0] && item.code === this.staffData[0].code) {
                    repeat = true;
                    return this.$message.error(this.$t('registrationList.addedStudents'));
                }
            });
            if (repeat === false) {
                this.staffData.forEach(item => {
                    this.selectedStaffList.push(item);
                });
                for (let i = 0; i < this.staffList.length; i++) {
                    for (let j = 0; j < this.staffData.length; j++) {
                        if (
                            this.staffList[i] &&
                            this.staffData[j] &&
                            this.staffList[i].code === this.staffData[j].code
                        ) {
                            this.staffList.splice(i, 1);
                        }
                    }
                }
                this.staffData = []
            }
        },
        // 右边表格选择项移到左边
        removeStaff() {
            setTimeout(() => {
                this.$refs["staffTable"].clearSelection();
                this.$refs["selectedStaffTable"].clearSelection();
            }, 0);
            if(this.selectedStaffData.length === 0) {
                return this.$message.error(this.$t('registrationList.pleaseRemovedStudents'))
            }
            this.selectedStaffData.forEach(item => {
                this.staffList.push(item);
            });
            for (let i = 0; i < this.selectedStaffList.length; i++) {
                for (let j = 0; j < this.selectedStaffData.length; j++) {
                    if (
                        this.selectedStaffList[i] &&
                        this.selectedStaffData[j] &&
                        this.selectedStaffList[i].code === this.selectedStaffData[j].code
                    ) {
                        this.selectedStaffList.splice(i, 1);
                    }
                }
            }
            this.selectedStaffData = []
        },
        // 将右边表格选择项存入selectedStaffData中
        handleSelectedStaffChange(rows) {
            this.selectedStaffData = [];
            if (rows) {
                rows.forEach(row => {
                    if (row) {
                        if(row.isLeader === 1) {
                            row.isLeader = null
                            this.radio = ''
                        }
                        this.selectedStaffData.push(row)
                    }
                });
            }
        },
        // 筛选
        onSubmit() {
            this.queryForm.pageNum_ = 1
            this.queryStudents()
            // this.postProjectInform(this.queryForm)
        },
        // 重置
        reset() {
            this.getDefaultGrade()
            for (let key in this.queryForm.condition) {
                if (key === 'form' || key === 'grade' || key === 'year') {
                    continue;
                }
                this.queryForm.condition[key] = '';
            }
            this.queryForm.condition.year = new Date().getFullYear()+''
            // this.options.approver = []
            this.queryForm.pageNum_ = 1
            this.queryStudents()
            this.getCompetitionNames()
        },
        // 保存
        save() {
            if (!this.queryForm.condition.year) {
                return this.$message.error(this.$t('registrationList.pleaseSelectYear'))
            }else if (!this.queryForm.condition.competitionId && this.compile === 'individual') {
                return this.$message.error(this.$t('registrationList.pleaseSelectCompetitionName'))
            }
            if (this.options.subName.length>0 && !this.queryForm.condition.subName) {
                // return this.$message.error('请选择竞赛小类')
                return this.$message.error(this.$t('registrationList.plzSelectCate'))
            }
            if(this.selectedStaffList.length > 0) {
                this.studentList = []
                this.selectedStaffList.forEach( item => {
                    this.studentList.push({
                        "studentId": item.code,
                        "studentName": item.name,
                        "telephone": item.telephone,
                        "mail": item.mail,
                        "isLeader": this.compile === 'team' ? item.isLeader : ''
                    })
                })
            } else {
                return this.$message.error(this.$t('registrationList.pleaseSelectStudents'))
            }
            if(this.compile === 'team') { // 人员变更
                // let leader = false // 是否有队长
                // for (const iterator of this.studentList) {
                //     if(iterator.isLeader) {
                //         leader = true
                //     }
                // }
                // if(leader) {
                    let params = {
                        "competitionId": this.dataInfo.competitionId,
                        "id": this.dataInfo.signRecordId,
                        "form": 1,
                        "studentList": this.studentList
                    }
                    competitionRegistrationApi.personChange(params).then(res => {
                        this.$message.success(this.$t('internship.successfully'))
                        this.studentList = []
                        this.selectedStaffList = []
                        this.$emit('change-exam')
                    })
                // } else {
                //     return this.$message.error(this.$t('registrationList.pleaseSelectCaptain'))
                // }
            } else { // 代理报名
                let params = {
                    "subId": this.queryForm.condition.subName?this.queryForm.condition.subName:null,
                    "competitionId": this.queryForm.condition.competitionId,
                    "form": 0,
                    "studentList": this.studentList
                }
                competitionRegistrationApi.agentSignUp(params).then(res => {
                    this.$message.success(this.$t('internship.successfully'))
                    this.studentList = []
                    this.selectedStaffList = []
                    this.$emit('change-exam')
                })
            }
        }
    },
}
</script>

<style lang="scss" scoped>
.el-breadcrumb__item:last-child ::v-deep {
    .el-breadcrumb__inner {
        color: #606266;
        font-weight: bold;
        cursor: default;
    }
}
.el-breadcrumb__item ::v-deep {
    .is-link {
        color: #aaa;
        font-weight: unset;
    }
    .is-link:hover {
        color: #409eff;
    }
}
</style>

